--http://delivery.admicro.vn/proxy?2;1;0;1;2656;1,5,3;kenh14.vn;/video/vo-chong-bang-kieu-di-an-khuya-voi-dong-nghiep-21691.chn?r=1351331898531vastversion;adtype;bannerid;locationid;zoneid;  (6) taglistid; (7) hostname ; (8) urlpath
--http://testing.logging.admicro.vn/proxy?2;1;0;1;2971;1,5,3;kenh14.vn;/video/vo-chong-bang-kieu-di-an-khuya-voi-dong-nghiep-21691.chn?r=1351331898531
-- Business Logic:
--          if banner_id>0 then get banner data from redis.
--          else get data banner using taglistid

local biz_name = "proxy"
local list_banner = "list_banner"
local data_banner = "data_banner"
local guid_freq ="frequency"
if test then
    ConfigRedisConnectors[data_banner]={
        host = test.host,
        port = test.port,
        queue = "Banner"
    }
    ConfigRedisConnectors[list_banner]={
        host = test.host,
        port = test.port,
        queue = "Target"
    }
    ConfigRedisConnectors[guid_freq]={
        host = test.host,
        port = test.port,
        queue = "Frequency"
    }
else
    ConfigRedisConnectors[data_banner]={
        --host = "192.168.2.28",
        --port = 6379,
        --host = "192.168.6.203",
        host = "192.168.5.201",
        --host = "192.168.5.141",
        port = 4338,
        queue = "Banners"
    }
    ConfigRedisConnectors[guid_freq]={
        --host = "192.168.2.28",
        --port = 6379,
        --host = "192.168.6.203",
        --host = "192.168.5.141",
        host = "192.168.5.201",
        port = 4338,
        queue = "Frequency"
    }
    ConfigRedisConnectors[list_banner]={
        --host = "192.168.6.203",
        --host = "192.168.5.141",
        host = "192.168.5.201",
        port = 4338,
        queue = "Target"
    }
end

local function tvc_vast()
return coroutine.create(function ()
--constants
local hget_list_banner = "hget "..ConfigRedisConnectors[list_banner].queue.." %s "
local hget_data_banner = "hget "..ConfigRedisConnectors[data_banner].queue.." %s "
local hget_guid_freq = "hget "..ConfigRedisConnectors[guid_freq].queue.." %s "
local cookie_domain = 		config.http.setcookie.pc
local http_server_name = 	config.http.servername
-- headers
local local_config = 		config
local SERVER_HEADER = 			local_config.SERVER_HEADER
local CACHE_CONTROL_HEADER = 	local_config.CACHE_CONTROL_HEADER
local EXPIRES_HEADER = 			local_config.EXPIRES_HEADER
local CONTENT_TYPE_HEADER = 	local_config.CONTENT_TYPE_HEADER
-- functions
local reply_pushHeader =	 	reply.pushHeader
local reply_ok =		 	 	reply.status_type.ok
local reply_setStatus = 	 	reply.setStatus
local request_getParams = 	 	request.getParams
local os_time = 				os.time
local to_number = 				tonumber
local util_redis_cmd = 			util.redis_cmd
local util_parse = 				util.parse
local util_parseLen = 			util.parseLen
local luredis_clear_buffer = 	luredis.clear_buffer
local luredis_concat_buffer = 	luredis.concat_buffer
local luredis_send_buffer = 	luredis.send_buffer
local luredis_send_cmd = 		luredis.send_cmd
local luredis_rs = 				luredis.reply_type.string
local coroutine_yield = 		coroutine.yield
local reply_appendContent = 	reply.appendContent
local request_getHeadersKV = request.getHeadersKV
local request_getParamsKV = request.getParamsKV

while true do
    reply_setStatus(reply_ok)
    -- get: bannerid;vastversion;taglistid;locationid;hostname;urlpath    
    local paraTable = request_getParams(";?")
    local p3 = paraTable[3]
    local banner_id = to_number(p3)
    local tag_id
    local p6 = paraTable[6] -- tag id list
    local xml
    

    if banner_id then
        if banner_id > 0  then
            xml = util_redis_cmd(data_banner,false,
                                        luredis_send_cmd, hget_data_banner, p3);
            tag_id = util_parseLen(p6,",",1)
        elseif banner_id == 0 then      
         	-- headers
		    local headerTable = request_getHeadersKV();
		    -- cookie
		    local cookieString = headerTable[config.COOKIE_HEADER];
		    local cookieTable = util.parseKV(cookieString,";=");
		    local guid = cookieTable[config.GUID_COOKIE];
            if not guid then
            	guid = "0"
            end
            
            local freqs = util_redis_cmd(guid_freq,false,
                                luredis_send_cmd,  hget_guid_freq, guid);
            local ftable = util.create_hashtable(freqs,",")
            local hgetkey = ""
            hgetkey = paraTable[5].."_"..paraTable[4].."_"
            for _,t in ipairs(util_parse(p6,",")) do
                local banners = util_redis_cmd(list_banner,false,
                                            luredis_send_cmd,hget_list_banner,hgetkey..t);
                if type(banners) == "string" and string.byte(banners,1) then
                    local ids = util_parse(banners,",")
                    local rnums = util.create_permutation(#ids)
                    for _,i in ipairs(rnums) do
                        if not ftable[ids[i]] then
                            xml = util_redis_cmd(data_banner,false,
                                                luredis_send_cmd,hget_data_banner,ids[i]);
                            if type(xml)=="string" then
                                tag_id = t
                                break
                            end
                        end
                    end
                end
                if tag_id then break end
            end
            if not tag_id then
                -- default banners
                local banners = util_redis_cmd(list_banner,false,
                                        luredis_send_cmd,hget_list_banner,"0_0_0");
                if type(banners) == "string" and string.byte(banners,1) then
                    local ids = util_parse(banners,",")
                    local rnums = util.create_permutation(#ids)
                    for _,i in ipairs(rnums) do
                        if not ftable[ids[i]] then
                            xml = util_redis_cmd(data_banner,false,
                                                luredis_send_cmd,hget_data_banner,ids[i]);
                            if type(xml)=="string" then break end
                        end
                    end
                end
                tag_id = "0"
            end
        end
    end

    if type(xml)=="string" and string.byte(xml,11) then
        local t = util_parse(xml,"{}")
        local len = #paraTable
        local zoneid = paraTable[5]
        local hostname
        local url
        if len == 8 then
            hostname = paraTable[7]
            url = ""
        else        
            hostname = paraTable[len-2]
            url = paraTable[len-1]
        end
        local labels = {["tagid"]=tag_id, ["zoneid"]=zoneid,["hostname"]= hostname, ["urlpath"]= url}
        for i,v in ipairs(t) do
            if labels[v] then t[i] = labels[v] end
        end
        reply_pushHeader(CONTENT_TYPE_HEADER, "text/xml")
        reply_pushHeader(CACHE_CONTROL_HEADER, "max-age=300, must-revalidate")
        reply_pushHeader(EXPIRES_HEADER,os.date("%a, %d-%b-%Y %H:%M:%S GMT",os.time()+300))
        reply_appendContent(table.concat(t,""))
    end
    coroutine_yield()
end
end)
end

creators[biz_name] = function()
        f[biz_name] = tvc_vast()
end
--[[
local replace_tagid = string.gsub(xml,"{tagid}",tag_id)
local replace_zoneid = string.gsub(replace_tagid,"{zoneid}", paraTable[4])
local len = #paraTable
local replace_hostname
local replace_urlpath
if len == 7 then
    replace_hostname = string.gsub(replace_tagid,"{hostname}", paraTable[len])
    replace_urlpath = string.gsub(replace_tagid,"{urlpath}", "")
else
    replace_hostname = string.gsub(replace_tagid,"{hostname}", paraTable[len])
    replace_urlpath = string.gsub(replace_tagid,"{urlpath}", paraTable[len-1])
end
reply_pushHeader(EXPIRES_HEADER,os.date("%a, %d-%b-%Y %H:%M:%S",os.time()+300))
reply_appendContent(replace_urlpath)]]
